<template>
  <div class="filter-form">
    <!-- 修改 Header -->
    <div class="header">
      <BaseButton @click="$router.push('/')">
        <ChevronsLeft/>
      </BaseButton>
      <span class="title">筛选</span>
      <div class="placeholder"></div>
    </div>

    <!-- 添加滾動容器 -->
    <div class="scroll-container">
      <div class="filter-content">
        <!-- 篩選 -->
        <div>
          <!-- 取件地址选择 -->
          <div class="form-item">
            <label class="label">选择取件地址</label>
            <div class="custom-select-wrapper" :data-open="pickupDropdownOpen">
              <input
                type="text"
                class="custom-select-input"
                v-model="pickup_address"
                @focus="togglePickupDropdown"
                placeholder="请选择或输入地址"
              />
              <div class="custom-select-dropdown" v-show="pickupDropdownOpen">
                <div 
                  v-for="option in pickupAddressOptions" 
                  :key="option"
                  class="item"
                  @click="handlePickupSelect(option)"
                >
                  {{ option === 'all' ? '所有地点' : option }}
                </div>
              </div>
            </div>
          </div>

          <!-- 送达地址选择 -->
          <div class="form-item">
            <label class="label">选择送达地址</label>
            <div class="custom-select-wrapper"  :data-open="deliveryDropdownOpen">
              <input
                type="text"
                class="custom-select-input"
                v-model="delivery_address"
                @focus="toggleDeliveryDropdown"
                placeholder="请选择或输入地址"
              />
              <div class="custom-select-dropdown" v-show="deliveryDropdownOpen">
                <div 
                  v-for="option in deliveryAddressOptions" 
                  :key="option"
                  class="item"
                  @click="handleDeliverySelect(option)"
                >
                  {{ option === 'all' ? '所有地点' : option }}
                </div>
              </div>
            </div>
          </div>

          <!-- 取件类型 -->
          <div class="form-item">
            <label class="label">取件类型</label>
            <div class="button-group">
              <button 
                v-for="type in pickupTypes" 
                :key="type.value"
                :class="{ active: pickup_type === type.value }"
                @click="togglePickupType(type.value)"
              >
                {{ type.label }}
              </button>
            </div>
          </div>

          <!-- 物件大小 -->
          <div class="form-item">
            <label class="label">物件大小</label>
            <div class="button-group">
              <button 
                v-for="item in sizes" 
                :key="item.value"
                :class="{ active: size === item.value }"
                @click="toggleSize(item.value)"
              >
                {{ item.label }}
              </button>
            </div>
          </div>

          <!-- 委托金额范围 -->
          <div class="form-item">
            <label class="label">委托金额范围</label>
            <div class="button-group grid-layout">
              <button 
                v-for="range in rewardRanges" 
                :key="range"
                :class="{ active: isActive(range) }"
                @click="toggleTotalAmount(range)"
              >
                {{ range }}
              </button>
            </div>
            <!-- 修改自定义区间输入样式 -->
            <div v-if="showCustomRange" 
                 class="custom-range"
                 :class="{ 'custom-range-active': isCustomRange }">
              <input 
                type="number" 
                v-model="customRange.min" 
                placeholder="最小金额"
                min="0"
              >
              <span>至</span>
              <input 
                type="number" 
                v-model="customRange.max" 
                placeholder="最大金额"
                min="0"
              >
              <span>元</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改确认按钮组 -->
    <div class="confirm-button">
      <button @click="cancelAndReturn">清空</button>
      <button @click="saveAndReturn">确认</button>
    </div>
  </div>

</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import BaseButton from '@/components/BaseButton.vue';
import { ChevronsLeft } from 'lucide-vue-next';

const router = useRouter()

// 修改初始值为 'all'，而不是空字符串
const pickup_address = ref('all')
const delivery_address = ref('all')
const pickup_type = ref('all')
const size = ref('all')
const total_amount = ref('all')

// 修改选项数组名称
const pickupAddressOptions = ['all','榕园', '荔园', '菜鸟驿站', '若海食堂',
'图书馆', '槿园', '华夏门']
const deliveryAddressOptions = ['all','榕园', '荔园', '菜鸟驿站', '若海食堂',
'图书馆', '槿园', '华夏门']
const pickupTypes = [
  { value: 1, label: '快递' },
  { value: 2, label: '外卖' }
]
const sizes = [
  { value: 1, label: '小' },
  { value: 2, label: '中' },
  { value: 3, label: '大' }
]
const rewardRanges = ['1-2元', '3-4元', '5-6元', '7-10元', '11-20元', '自定义']
const customRange = ref({ min: '', max: '' })
const showCustomRange = ref(false)

// 添加初始化函数，在组件挂载时读取本地存储的筛选条件
onMounted(() => {
  const savedFilters = JSON.parse(localStorage.getItem('filters') || '{}')
  pickup_address.value = savedFilters.pickup_address || 'all'
  delivery_address.value = savedFilters.delivery_address || 'all'
  pickup_type.value = savedFilters.pickup_type || 'all'
  size.value = savedFilters.size || 'all'
  total_amount.value = savedFilters.total_amount || 'all'

  // 如果之前选择了自定义范围，需要还原自定义输入框的值
  if (savedFilters.total_amount?.includes('-') && savedFilters.custom_range) {
    total_amount.value = '自定义'
    showCustomRange.value = true
    customRange.value = {
      min: savedFilters.custom_range.min,
      max: savedFilters.custom_range.max
    }
  }
})

// 修改 watch 监听
watch(pickup_address, (val) => console.log('取件地址:', val))
watch(delivery_address, (val) => console.log('送达地址:', val))
watch(pickup_type, (val) => console.log('取件类型:', val))
watch(size, (val) => console.log('物件大小:', val))
watch(total_amount, (val) => console.log('委托金额:', val))

// 监听金额范围变化
watch(total_amount, (newVal) => {
  handleCustomRange()
})

// 修改保存方法
const saveAndReturn = () => {
  // 检查并格式化自定义金额区间
  let amountValue = total_amount.value
  if (total_amount.value === '自定义') {
    const min = Number(customRange.value.min)
    const max = Number(customRange.value.max)
    
    // 验证输入的金额
    if (!min || !max || min < 0 || max < 0 || min > max) {
      alert('请输入有效的金额区间')
      return
    }
    
    amountValue = `${min}-${max}元`
  }

  const filters = {
    pickup_address: pickup_address.value,
    delivery_address: delivery_address.value,
    pickup_type: pickup_type.value,
    size: size.value,
    total_amount: amountValue,
    // 添加自定义区间的具体数值，方便列表页面筛选使用
    custom_range: total_amount.value === '自定义' ? {
      min: Number(customRange.value.min),
      max: Number(customRange.value.max)
    } : null
  }
  
  localStorage.setItem('filters', JSON.stringify(filters))
  router.push('/')
}

// 添加取消方法
const cancelAndReturn = () => {
  // 重置所有筛选条件为默认值
  pickup_address.value = 'all'
  delivery_address.value = 'all'
  pickup_type.value = 'all'
  size.value = 'all'
  total_amount.value = 'all'
  
  // 清除本地存储的筛选条件
  localStorage.removeItem('filters')
}

// 添加切换函数
const togglePickupType = (value) => {
  pickup_type.value = pickup_type.value === value ? 'all' : value
}

const toggleSize = (value) => {
  size.value = size.value === value ? 'all' : value
}

const toggleTotalAmount = (value) => {
  total_amount.value = total_amount.value === value ? 'all' : value
}

// 添加自定义区间处理方法
const handleCustomRange = () => {
  if (total_amount.value === '自定义') {
    showCustomRange.value = true
  } else {
    showCustomRange.value = false
  }
}

// 添加检查是否为自定义范围的方法
const isCustomRange = computed(() => {
  return total_amount.value === '自定义'
})

// 修改判断是否激活的逻辑
const isActive = (value) => {
  if (value === '自定义') {
    return showCustomRange.value
  }
  return total_amount.value === value
}

// 新增自定义下拉栏逻辑
const openDropdown = ref(false)
const currentLabel = ref('请选择')
const options = [
  { value: '1', label: '选项 1' },
  { value: '2', label: '选项 2' },
  { value: '3', label: '选项 3' }
]

function toggleDropdown() {
  openDropdown.value = !openDropdown.value
}

function handleSelect(option) {
  currentLabel.value = option.label
  openDropdown.value = false
}

// 添加下拉框控制状态
const pickupDropdownOpen = ref(false)
const deliveryDropdownOpen = ref(false)

// 添加选择函数
function togglePickupDropdown() {
  pickupDropdownOpen.value = !pickupDropdownOpen.value
  deliveryDropdownOpen.value = false // 关闭另一个下拉框
}

function toggleDeliveryDropdown() {
  deliveryDropdownOpen.value = !deliveryDropdownOpen.value
  pickupDropdownOpen.value = false // 关闭另一个下拉框
}

function handlePickupSelect(option) {
  pickup_address.value = option
  pickupDropdownOpen.value = false
}

function handleDeliverySelect(option) {
  delivery_address.value = option
  deliveryDropdownOpen.value = false
}

// 添加点击外部关闭下拉框
onMounted(() => {
  document.addEventListener('click', (e) => {
    if (!e.target.closest('.custom-select-wrapper')) {
      pickupDropdownOpen.value = false
      deliveryDropdownOpen.value = false
    }
  })
})

</script>

<style scoped>


/* 字体通用样式 */
.text-base {
  font-size: var(--font-small);
  color: #333333;
  line-height: 1.5;
  font-family: 'SourceHanFont', sans-serif;
}

.text-title {
  font-size: var(--font-large);
  font-weight: 600;
  letter-spacing: 0.5px;
  color: #333333;
  font-family: var(--font-family-bold);
}

.text-label {
  font-size: var(--font-small);
  font-weight: 600;
  color: #333333;
  margin-bottom: 12px;
  font-family: var(--font-family-bold);
}

.text-button {
  font-size: var(--font-small);
  font-weight: 500;
  font-family: var(--font-family-normal);
}

/* 更新现有样式 */
.title {
  font-size: var(--font-large);
  letter-spacing: 0.5px;
  color: #333333;
  font-family:'SourceHanFontBold', sans-serif;
}

.label {
  font-size: var(--font-small);
  font-family: var(--font-family-bold);
  color: #333333;
  margin-bottom: 12px;

  display: block;
  margin-bottom: 16px;
  letter-spacing: 0.5px;
  color: #333; /* 确保文字颜色为深色 */
}

.select-wrapper {
  position: relative;
  width: 100%;
  max-width: 240px;
  background: transparent;
}

/* 选择框本体样式 */
select {
  width: 100%;  /* 使用100%确保与wrapper同宽 */
  padding: 10px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background: #ffffff;
  color: #333;
  font-size: var(--font-small);
  font-family: var(--font-family-bold);
  cursor: pointer;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
}

/* 下拉列表样式 */
/* select option {
  width: 60%;  
  padding: 12px 15px;
  font-size: var(--font-small);
  color: #333;
  background: #ffffff;
  cursor: pointer;
} */

/* 下拉箭头样式 */
.select-wrapper::after {
  content: "";
  position: absolute;
  right: 15px;
  top: 50%;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid #666;
  transform: translateY(-50%);
  pointer-events: none;
}

select:hover {
  border-color: #a5b2e5;
}

select:focus {
  outline: none;
  border-color: #a5b2e5;
  box-shadow: 0 0 0 2px rgba(165,178,229,0.1);
}

option {
  padding: 5px;
  background-color: #f9f9f9;
  color: #333;
}

button {
  font-size: var(--font-small);
  font-weight: 500;
  font-family: var(--font-family-normal);
  padding: 10px 20px;
  border: none;
  border-radius: 12px;  /* 减小选项按钮的圆角 */
  background: #f5f5f5;
  color: #333;
  cursor: pointer;
  transition: all 0.3s ease;
}

button:hover {
  background: #e8e8e8;
  transform: translateY(-1px);
}

button.active {
  background: #9dbce3;  /* 修改为新的颜色 */
  color: white;
  box-shadow: 0 2px 8px rgba(157, 188, 227, 0.4);  /* 更新阴影颜色以匹配新的背景色 */
}

.confirm-button button {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
  margin: 0 8px;
  padding: 14px 24px;
  letter-spacing: 0.5px;
}

.confirm-button button:first-child {
  background: #f5f5f5;
  color: #666;
  margin-right: 12px;
}

.confirm-button button:last-child {
  background: #9dbce3;  /* 确认按钮背景色 */
  color: #ffffff;      /* 确认按钮文字颜色 */
  margin-left: 12px;
  box-shadow: 0 4px 12px rgba(157, 188, 227, 0.3);
}

.confirm-button button:last-child:hover {
  background: #8badd4;  /* 添加略深的悬停颜色 */
}

.scroll-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 90px; /* 增加底部内边距，确保内容不被底部按钮遮挡 */
}

.filter-content {
  height: 100%;
  padding: 0 16px;
}

.custom-range {
  margin-top: 15px;
  padding: 15px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.custom-range input {
  font-size: var(--font-small);
  color: #333333;
  line-height: 1.5;
  font-family: 'SourceHanFontBold', sans-serif;
  width: 100px;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  text-align: center;
  transition: all 0.3s ease;
}

.custom-range input:focus {
  border-color: #a5b2e5;
  outline: none;
  box-shadow: 0 0 0 2px rgba(165,178,229,0.2);
}

.custom-range span {
  font-size: var(--font-small);
  color: #333333;
  line-height: 1.5;
  font-family: 'SourceHanFontBold', sans-serif;
  color: #666;
  margin: 0 8px;
}

.custom-range-active {
  background: #f8faff;
  border: 1px solid #a5b2e5;
}

.custom-range-active input {
  border-color: #bdbdbd;
  color: #000; /* 选中状态时保持文字黑色 */
}

.custom-range-active span {
  color: #000; /* 选中状态时保持文字黑色 */
}

.filter-form {
  max-width: 100%;
  width: 100%;
  height: 100%;
  background-color:rgba(242, 241, 246, 1) !important;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 20px;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.back-btn {
  padding: 10px;
  background: none;
  border: none;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.back-btn:active {
  transform: scale(0.95);
}

.back-btn img {
  width: 20px;
  height: 20px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 0.5px;
  color: #333;
}

.placeholder {
  width: 20px;
}

.form-item {
  padding: 25px 20px;
  margin: 15px 0;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

/* 这里控制整个下拉框容器的宽度 */
.select-wrapper {
  position: relative;
  width: 100%;          /* 这里是相对父元素的宽度 */
  max-width: 240px;     /* ← 这里限制了下拉框的最大宽度 */
  background: transparent;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 5px;
}

.grid-layout {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.confirm-button {
  position: relative;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  padding: 12px;
  background: white;
  box-shadow: 0 -4px 12px rgba(0,0,0,0.08);
  display: flex;
  justify-content: space-between;
  z-index: 100;
}

/* 新增自定义下拉样式 */
.custom-select-wrapper {
  position: relative;
  width: 100%;
  max-width: 240px;
}

.custom-select-display {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background: #ffffff;
  cursor: pointer;
  font-family: var(--font-family-bold);
  font-size: var(--font-small);
  color: #333;
  position: relative;
  transition: all 0.2s ease;
}

/* 下拉框打开时的本体样式 */
.custom-select-wrapper[data-open="true"] .custom-select-display {
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
  border-bottom-color: transparent;
}

.custom-select-display::after {
  content: "";
  position: absolute;
  right: 15px;
  top: 50%;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid #666;
  transform: translateY(-50%);
}

.custom-select-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background: #ffffff;
  border: 1px solid #dcdfe6;
  border-top: none; /* 移除上边框 */
  border-top-left-radius: 0; /* 移除上部圆角 */
  border-top-right-radius: 0;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
  margin-top: 0;  /* 修改这里，从 4px 改为 0 */
  box-shadow: none; /* 移除阴影 */
  z-index: 999;
  max-height: 200px;
  overflow-y: auto;
}

.custom-select-dropdown .item {
  padding: 10px 15px;
  cursor: pointer;
  font-family: var(--font-family-bold);
  font-size: var(--font-small);
  color: #333;
}

.custom-select-dropdown .item:hover {
  background: #f5f7fa;
}

/* 修改输入框样式 */
.custom-select-input {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background: #ffffff;
  font-family: var(--font-family-bold);
  font-size: var(--font-small);
  color: #333;
  transition: all 0.2s ease;
}

.custom-select-wrapper[data-open="true"] .custom-select-input {
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
  border-bottom-color: transparent;
}

</style>